package osmparser;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Willy Tiengo
 */
public class OSMParser {

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static OSMDoc parse(String path) throws Exception {

		Document doc;
		DocumentBuilder builder;

		Node node;
		NodeList nodesList;

		Map<String, OSMNode> nodesMap = new HashMap<String, OSMNode>();
		Map<String, OSMWay> waysMap = new HashMap<String, OSMWay>();
		Map<String, OSMRelation> relationsMap = new HashMap<String, OSMRelation>();

		builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		doc = builder.parse(path);

		nodesList = doc.getChildNodes().item(0).getChildNodes();

		for (int i = 0; i < nodesList.getLength(); i++) {

			node = nodesList.item(i);

			if (NodeParser.isNode(node)) {

				OSMNode osmNode = NodeParser.parseNode(node);
				nodesMap.put(osmNode.id, osmNode);

			} else if (WayParser.isWay(node)) {
				OSMWay way = WayParser.parseWay(node, nodesMap);
				waysMap.put(way.id, way);

			} else if (RelationParser.isRelation(node)) {
				OSMRelation relation = RelationParser.parseRelation(node,
						nodesMap, waysMap);
				relationsMap.put(relation.id, relation);

			}
		}

		OSMDoc osm = new OSMDoc(nodesMap, waysMap, relationsMap);
		return osm;
	}

	protected static Map<String, String> parseTags(NodeList nodes) {

		Map<String, String> tags = new HashMap<String, String>();

		for (int i = 0; i < nodes.getLength(); i++) {

			Node node = nodes.item(i);

			if (node.getNodeName().equals("tag")) {

				addTag(tags, node);

			}
		}

		return tags;
	}

	private static void addTag(Map<String, String> tags, Node node) {
		String key = node.getAttributes().getNamedItem("k").getNodeValue();
		String value = node.getAttributes().getNamedItem("v").getNodeValue();

		if (tags.get(key) != null) {

			tags.put(key, tags.get(key) + ";" + value);

		} else {

			tags.put(key, value);

		}
	}
}
